package com.siyoumi.app.service;

import com.siyoumi.app.entity.WxQr;
import com.siyoumi.app.mapper.WxQrMapper;
import com.siyoumi.app.sys.service.wxapi.WxApiApp;
import com.siyoumi.exception.XException;
import com.siyoumi.service.ServiceImplBase;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XReturn;
import com.siyoumi.component.XSpringContext;
import com.siyoumi.util.XStr;
import com.siyoumi.component.http.InputData;
import com.siyoumi.component.http.XHttpContext;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


//t_wx_qr
@Service
public class WxQrService
        extends ServiceImplBase<WxQrMapper, WxQr> {
    static public WxQrService getBean() {
        return XSpringContext.getBean(WxQrService.class);
    }

    @Override
    public XReturn saveEntityBefore(InputData inputData, WxQr entity) {
        Boolean hyaline = inputData.input("is_hyaline", "0").equals("1");

        entity.setWxqr_key(null);
        if (inputData.isAdminAdd()) {
            entity.setWxqr_type("wxapp");
        }

        if (XStr.isNullOrEmpty(entity.getWxqr_info())) {
            XLog.debug(this.getClass(), "接口生成小程序码");

            Map<String, Object> dataAppend = new HashMap<>();
            dataAppend.put("is_hyaline", hyaline); //透明底

            WxApiApp miniProgram = WxApiApp.getIns(XHttpContext.getXConfig(true));
            XReturn r = miniProgram.getQrCode(entity.getWxqr_path(), dataAppend);
            if (r.err()) {
                throw new XException(r);
            }

            String fileVal = r.getData("file_val");
            entity.setWxqr_info(fileVal);
        }

        return super.saveEntityBefore(inputData, entity);
    }
}
